package com.yunatt.aspect;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
@Slf4j
public class AutoLogAspectV2 {

    @Pointcut("execution(public * com.yunatt.controller..*Controller.*(..))")
    public void logPointCut() {}

    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        //获取request
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        TimeInterval timer = DateUtil.timer();
        //执行方法
        log.info("请求真实IP地址为：【{}】接口为【{}】,请求参数为【{}】", ServletUtil.getClientIP(request),
                request.getRequestURL().toString(), StrUtil.maxLength(JSONUtil.toJsonStr(ServletUtil.getParamMap(request)), 1000));
        Object result = point.proceed();
        try {
            //执行时长(毫秒)
            log.info("接口为【{}】,返回结果为：【{}】,耗时为：【{}】", request.getRequestURL().toString(),
                    StrUtil.maxLength(JSONUtil.toJsonStr(result), 2000), timer.interval());
        } catch (Exception e) {
            log.error("切面发生异常");
        }
        return result;
    }
}

